const webpack = require('webpack')
const fs = require('fs')
const path = require('path')
const dll = require('./webpack.dll.config')

if (process.env.NODE_ENV !== 'development') {
  const lastVersionPath = path.join(__dirname, 'last_version')
  if (!fs.existsSync(lastVersionPath)) {
    throw new Error('last_version 文件不存在，无法继续构建。若初次构建请创建此文件并写入内容为当前版本号减一。')
  }
  const lastVersion = parseInt(fs.readFileSync(lastVersionPath))
  const currentVersion = parseInt(process.env.VUE_APP_VERSION)
  if (currentVersion <= lastVersion) {
    throw new Error('当前版本必须大于上一次构建时的版本！您可能忘了修改当前版本号，请在.env中修改。若是由于误操作构建，请修改 lastVersion 文件的内容')
  }
  fs.writeFileSync(lastVersionPath, currentVersion.toString())
}

function buildProxy(list) {
  const proxy = {}
  for (const key of list) {
    proxy[key] = {
      target: process.env.BACKEND,
      ws: false,
      changeOrigin: true
    }
  }
  return proxy
}

const dllPlugins = []
for (const name in dll.entry) {
  dllPlugins.push(new webpack.DllReferencePlugin({
    context: __dirname,
    manifest: require(`./dll/${name}-manifest.json`)
  }))
}

module.exports = {
  outputDir: process.env.OUTPUT_DIR,
  assetsDir: '',
  publicPath: process.env.PUBLIC_PATH, // 相对路径，Cordova等应用需要此配置
  productionSourceMap: false,
  devServer: {
    proxy: buildProxy(['/api', '/uploads'])
  },
  configureWebpack: {
    plugins: [
      ...dllPlugins
      // new webpack.HtmlWebpackPlugin({
      //   chunks: [path.join(__dirname, './public/js/index.js')]
      // })
    ]
  }
}
